package net.loyintean.pearlshell.wechat.messagepasser.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import net.loyintean.pearlshell.wechat.common.MessageTypeEnum;
import net.loyintean.pearlshell.wechat.messagepasser.AbstractMessageBuilder;
import net.loyintean.pearlshell.wechat.messagepasser.IMessageParser;
import net.loyintean.pearlshell.wechat.model.BaseMessageModel;

public class MessageParserImpl implements IMessageParser {

	private Map<String, AbstractMessageBuilder> builderMap;

	public MessageParserImpl() {
		builderMap = new HashMap<String, AbstractMessageBuilder>();

		builderMap.put(MessageTypeEnum.text.name(),
				new TextMessageBuilderImpl());
	}

	@Override
	public BaseMessageModel parse(ServletRequest request) {
		assert request != null;

		BaseMessageModel baseMessage = null;

		try {
			// 从request中取得输入流
			InputStream inputStream = request.getInputStream();
			// 读取输入流
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);

			baseMessage = buildMessageModel(document);

		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return baseMessage;
	}

	private BaseMessageModel buildMessageModel(Document document) {
		BaseMessageModel baseMessage;

		AbstractMessageBuilder builder = new BaseMessageBuilderImpl();

		baseMessage = builder.getMessage(document);

		builder = AbstractMessageBuilder.getBuilder(baseMessage.getMsgType());

		if (builder != null) {

			baseMessage = builder.getMessage(document);
		}

		return baseMessage;

	}
}
